package com.chenfan.mcn.rule;

import com.chenfan.mcn.clients.privilege.DepartmentVO;
import com.chenfan.mcn.clients.privilege.SUser;
import com.chenfan.mcn.constant.NumberCst;
import com.chenfan.mcn.enums.DeleteEnum;
import com.chenfan.mcn.extension.rule.ComputableRule;
import com.chenfan.mcn.model.BusinessCommissionDetailTemporary;
import com.chenfan.mcn.model.CustomerTarget;
import com.chenfan.mcn.model.DepartmentTarget;
import com.chenfan.mcn.model.vo.QuarterIncomeContractVO;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 个人佣金率（总提点）规则集
 *
 * @author wulg
 * @date 2021-09-17
 **/
public class BusinessCommissionV1Rule implements ComputableRule<BusinessCommissionRuleContext, List<BusinessCommissionDetailTemporary>> {

    private final static BigDecimal PERCENT_30 = new BigDecimal("0.3");

    private final static BigDecimal PERCENT_2 = new BigDecimal("0.02");

    private final static BigDecimal PERCENT_1 = new BigDecimal("0.01");

    private final static BigDecimal PERCENT_1_POINT_5 = new BigDecimal("0.015");

    private final static BigDecimal PERCENT_POINT_5 = new BigDecimal("0.005");

    /**
     * 组装提成人明细数据
     * @param context     上下文
     */
    @Override
    public List<BusinessCommissionDetailTemporary> execute(BusinessCommissionRuleContext context) {
        QuarterIncomeContractVO x = context.getQuarterIncomeContractVO();
        BusinessCommissionDetailTemporary temporary = new BusinessCommissionDetailTemporary();
        temporary.setIncomeCode(x.getContractCode());
        temporary.setIncomeId(x.getId());
        temporary.setCustomerId(x.getCustomerId());
        temporary.setBusinessAmount(x.getBusinessAmount());
        temporary.setPayBackStatus(x.getPayBackStatus());
        temporary.setSignDate(x.getSignDate());
        temporary.setCustomerScore(context.getBaseCustomer(x.getCustomerId()).getCustomerScore());
        temporary.setCustomerFirstOrder(x.getCustomerFirstOrder() ? NumberCst.ONE : NumberCst.ZERO);
        temporary.setCommissionId(x.getOwnerId());
        temporary.setCommissionName(x.getOwnerName());
        temporary.setCreateDate(x.getCreateDate());
        temporary.setCreateBy(x.getOperatorId());
        temporary.setIsDelete(DeleteEnum.FALSE.getValue());
        temporary.setIsSave(NumberCst.ZERO);
        temporary.setIsInvalid(NumberCst.ZERO);
        temporary.setTemporaryCode(context.getTemporaryCode());
        this.customerTargetAchievementRate(temporary, x, context);
        BigDecimal projectSales = x.getBusinessAmount().multiply(PERCENT_30).setScale(2, BigDecimal.ROUND_HALF_UP);
        temporary.setProjectSales(projectSales);
        this.departmentTargetAchievementRate(temporary, x, context);
        if (Objects.nonNull(x.getOwnerId()) && Objects.nonNull(context.getSuser(x.getOwnerId()))) {
            temporary.setJobNumber(context.getSuser(x.getOwnerId()).getJobNumber());
        }
        if (Objects.nonNull(x.getDepartmentHeaderId()) && Objects.nonNull(context.getSuser(x.getDepartmentHeaderId()))) {
            temporary.setDepartmentJobNumber(context.getSuser(x.getDepartmentHeaderId()).getJobNumber());
        }
        boolean customerFirstOrder = x.getCustomerFirstOrder().booleanValue();
        SUser sUser = context.getSuser(x.getOwnerId());
        if(sUser == null || sUser.getStatus().equals(NumberCst.ONE) || sUser.getStatus().equals(NumberCst.TWO)) {
            //离职
            temporary.setGeneralPoints(BigDecimal.ZERO);
        } else {
            //在职
            if (!customerFirstOrder && NumberCst.ONE.equals(x.getPerformanceShare())) {
                temporary.setGeneralPoints(PERCENT_1);
            } else if (customerFirstOrder && NumberCst.ONE.equals(x.getPerformanceShare())) {
                temporary.setGeneralPoints(PERCENT_1_POINT_5);
            } else if (customerFirstOrder && NumberCst.ZERO.equals(x.getPerformanceShare())) {
                temporary.setGeneralPoints(PERCENT_2);
            } else {
                temporary.setGeneralPoints(PERCENT_1);
            }
        }
        BigDecimal personalCommission = temporary.getProjectSales().multiply(temporary.getGeneralPoints())
                .multiply(temporary.getTargetAchievementRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
        temporary.setPersonalCommission(personalCommission);
        //业绩共享人
        if (NumberCst.ONE.equals(x.getPerformanceShare())) {
            BusinessCommissionDetailTemporary sharerTemporary = new BusinessCommissionDetailTemporary();
            BeanUtils.copyProperties(temporary, sharerTemporary);
            sharerTemporary(sharerTemporary, x, context);
            return Arrays.asList(temporary, sharerTemporary);
        }
        return Arrays.asList(temporary);
    }

    /**
     * 部门目标达成率
     * @param temporary
     * @param x
     * @param context
     */
    private void departmentTargetAchievementRate(BusinessCommissionDetailTemporary temporary, QuarterIncomeContractVO x, BusinessCommissionRuleContext context) {
        DepartmentVO departmentVO = context.getDepartmentVO(x.getOwnerId());
        Long backupDepartmentHeadId = departmentVO != null ? departmentVO.getDepartmentHeadId() : null;
        String backupDepartmentHeadName = departmentVO != null ? departmentVO.getDepartmentHeadName() : null;
        temporary.setDepartmentHeadId(Objects.nonNull(x.getDepartmentHeaderId()) ? x.getDepartmentHeaderId() : backupDepartmentHeadId);
        temporary.setDepartmentHeadName(Objects.nonNull(x.getDepartmentHeaderName()) ? x.getDepartmentHeaderName() : backupDepartmentHeadName);
        DepartmentTarget departmentTarget = context.getDepartmentTarget(x.getQuarterCode(), x.getDepartmentId());
        if (Objects.nonNull(departmentTarget) && Objects.nonNull(departmentTarget.getTargetReachRate())) {
            temporary.setDepartmentTargetAchievementRate(departmentTarget.getTargetReachRate());
        } else {
            temporary.setDepartmentTargetAchievementRate(BigDecimal.ZERO);
        }
        if (Objects.nonNull(temporary.getDepartmentHeadId()) && temporary.getDepartmentHeadId().longValue() != temporary.getCommissionId().longValue()) {
            Integer userStatus = context.getSuser(temporary.getDepartmentHeadId()).getStatus();
            if(userStatus.equals(NumberCst.ONE) || userStatus.equals(NumberCst.TWO)) {
                temporary.setDepartmentHeadCommissionPoint(BigDecimal.ZERO);
            } else {
                temporary.setDepartmentHeadCommissionPoint(PERCENT_1);
            }
            BigDecimal departmentHeadCommission = temporary.getProjectSales().multiply(temporary.getDepartmentHeadCommissionPoint()).setScale(2, BigDecimal.ROUND_HALF_UP);
            temporary.setDepartmentHeadCommission(departmentHeadCommission);
        }
        else {
            temporary.setDepartmentHeadCommissionPoint(BigDecimal.ZERO);
            temporary.setDepartmentHeadCommission(BigDecimal.ZERO);
        }
    }

    /**
     * （客户）目标达成率
     * @param temporary
     * @param x
     * @param context
     */
    private void customerTargetAchievementRate(BusinessCommissionDetailTemporary temporary, QuarterIncomeContractVO x, BusinessCommissionRuleContext context) {
        CustomerTarget customerTarget = context.getCustomerTarget(x.getQuarterCode(), x.getCustomerId());
        temporary.setKeyCustomers(Objects.nonNull(customerTarget) ? NumberCst.ZERO : NumberCst.ONE);
        if (Objects.isNull(customerTarget)) {
            temporary.setTargetAchievementRate(BigDecimal.ONE);
        } else if (Objects.isNull(customerTarget.getTargetReachRate())) {
            temporary.setTargetAchievementRate(BigDecimal.ZERO);
        } else if(customerTarget.getTargetReachRate().compareTo(BigDecimal.ONE) == 1) {
            temporary.setTargetAchievementRate(BigDecimal.ONE);
        } else {
            temporary.setTargetAchievementRate(customerTarget.getTargetReachRate());
        }
    }

    /**
     * 共享人提成数据组装
     *
     * @param sharerTemporary    {@link BusinessCommissionDetailTemporary}
     * @param x            {@link QuarterIncomeContractVO}
     * @param context         {@link BusinessCommissionRuleContext}
     */
    private void sharerTemporary(BusinessCommissionDetailTemporary sharerTemporary, QuarterIncomeContractVO x, BusinessCommissionRuleContext context) {
        SUser sUser = context.getSuser(x.getPerformanceSharerId());
        if(sUser == null || sUser.getStatus().equals(NumberCst.ONE) || sUser.getStatus().equals(NumberCst.TWO)) {
            //离职
            sharerTemporary.setGeneralPoints(BigDecimal.ZERO);
        } else {
            //在职
            sharerTemporary.setGeneralPoints(PERCENT_POINT_5);
        }
        BigDecimal personalCommission = sharerTemporary.getProjectSales().multiply(sharerTemporary.getGeneralPoints()).multiply(sharerTemporary.getTargetAchievementRate())
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        sharerTemporary.setPersonalCommission(personalCommission);
        sharerTemporary.setCommissionId(x.getPerformanceSharerId());
        sharerTemporary.setCommissionName(x.getPerformanceSharerName());
        sharerTemporary.setDepartmentHeadCommissionPoint(BigDecimal.ZERO);
        sharerTemporary.setDepartmentHeadCommission(BigDecimal.ZERO);
        if (Objects.nonNull(x.getPerformanceSharerId()) && Objects.nonNull(context.getSuser(x.getPerformanceSharerId()))) {
            sharerTemporary.setJobNumber(context.getSuser(x.getPerformanceSharerId()).getJobNumber());
        }
    }
}